<?php
/**
 * Created by PhpStorm.
 * User: mohuani
 * Date: 2019/4/13
 * Time: 19:16
 */

namespace App\Jobs;

use App\Utils\Util;

//require_once "../App/Utils/Autoloader.php";



class GetWeatherByCityKeyJob implements BaseJob
{
    /** @var Util|null  */
    private static $util = null;

    /** @var object|\Redis|null  */
    private static $redis = null;

    /**
     * GetWeatherByCityKeyJob constructor.
     */
    public function __construct()
    {
        // 初始化 $util，$redis对象
        if (self::$util == null) {
            self::$util = new Util();
        }

        if (self::$redis == null) {
            self::$redis = self::$util->getRedis();
        }
    }


    public function handle()
    {
        // TODO: Implement handle() method.

        // 创建curl句柄，$util句柄
        $curl = curl_init();

//        $url = WEATHER_API_BY_CITY_KEY . "101280601";
//        $curlRes = self::$util->curlRequest($curl, $url);
//        $curlRes = json_decode($curlRes, true);
//        if ($curlRes['status'] == WEATHER_API_OK_STATUS_CODE) {
//            self::$redis->setex(WEATHER_INFO_CITY_KEY_REDIS_KEY . '101280601', WEATHER_INFO_REDIS_EXPIRE_TIME, json_encode($curlRes['data'], JSON_UNESCAPED_UNICODE));
//        } else {
//            var_dump("cityKey:" . '101280601' . " | msg:天气信息查询失败 | url:" . $url);
//        }
//        curl_close($curl);
//        exit();


        // 获取城市列表，循环取每个城市的天气数据
        $cityListFile = self::$util->getCityLists();
        if (!empty($cityListFile) && is_array($cityListFile)) {
            $i = 0;
            foreach ($cityListFile['xml']['d'] as $cityListFileK => $cityListFileV) {
//                $url = WEATHER_API_BY_CITY_KEY . "101280601";
                $url = WEATHER_API_BY_CITY_KEY . $cityListFileV['-d1'];  //

                $curlRes = self::$util->curlRequest($curl, $url);
                var_dump($curlRes);
                $curlRes = json_decode($curlRes, true);
                if (isset($curlRes['status']) && $curlRes['status'] == WEATHER_API_OK_STATUS_CODE) {
                    self::$redis->setex(WEATHER_INFO_CITY_KEY_REDIS_KEY . $cityListFileV['-d1'], WEATHER_INFO_REDIS_EXPIRE_TIME, json_encode($curlRes['data'], JSON_UNESCAPED_UNICODE));
                } else {
                    var_dump("cityKey:" . $cityListFileV['-d1'] . " | msg:天气信息查询失败 | url:" . $url);
                }

                $i += 1;
                var_dump($i);
//                exit();
            }
        } else {
            var_dump("城市列表获取失败");
        }

        // 关闭相关资源
        curl_close($curl);
    }

}